package com.piece.core.web.interceptor;

import com.piece.core.framework.constant.CookieConstants;
import com.piece.core.web.cookie.CookieUtil;
import com.piece.core.web.util.ServletUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 上下文拦截器
 */
public class ContextInterceptor extends HandlerInterceptorAdapter {

    @Value("${spring.resources.context:#{'/'}}")
    private String contextPath;

    @Autowired
    private InterceptorHookManager interceptorHookManager;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        this.interceptorHookManager.preHandle(request, response, handler);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        CookieUtil.setCookie(request, response, CookieConstants.CTX, ServletUtil.getRequestPrefix(contextPath), false);
        request.setAttribute(CookieConstants.CTX, request.getContextPath() + contextPath);
        request.setAttribute(CookieConstants.LANGUAGE, LocaleContextHolder.getLocale().toLanguageTag());
        this.interceptorHookManager.postHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
        this.interceptorHookManager.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        super.afterConcurrentHandlingStarted(request, response, handler);
        this.interceptorHookManager.afterConcurrentHandlingStarted(request, response, handler);
    }
}
